<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Infotech Ltd.
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2006/04/05 19:58:31 $)
// $RCSfile: visitor_htmlcode.php,v $ : $Revision: 1.24 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

$template->cache(array('proactivechatdiv', 'chatimage'));
$template->loadLanguageSection("livesupportclient");

header("Content-Type: text/javascript");
if ($_SWIFT["settings"]["livesupport_cachehtmljscode"] == "1")
{
	headerCache();
} else {
	headerNoCache();
}

// ======= Load Up the functions file =======
require_once ("./modules/livesupport/functions_livesupport.php");

$_staffstatus = isStaffMonitorOnline($_GET["departmentid"]);
if ($_staffstatus == STATUS_ONLINE)
{
	$template->assign("staffstatus", "online");
	$template->assign("staffstatustext", $_SWIFT["language"]["clickforlivesupport"]);
} else if ($_staffstatus == STATUS_AWAY) {
	$template->assign("staffstatus", "away");
	$template->assign("staffstatustext", $_SWIFT["language"]["lsisaway"]);
} else if ($_staffstatus == STATUS_BACK) {
	$template->assign("staffstatus", "back");
	$template->assign("staffstatustext", $_SWIFT["language"]["lsbacksoon"]);
} else {
	$template->assign("staffstatus", "offline");
	$template->assign("staffstatustext", $_SWIFT["language"]["clickleavemessage"]);
}

if ($_GET["nolink"] == 1)
{
	$template->assign("nolink", 1);
}

// Does this user have a session id set?
$cookiesessionid = $cookie->getSCookie("sessionid".SESSION_VISITOR);
if (trim($cookiesessionid) == "")
{
	$sessionid = $session->insertSession(SESSION_VISITOR);
} else {
	$sessionid = $cookiesessionid;
}

$cookiebuild = false;
$cookie->parseCookie("visitor");
// Does this person have a country code set in cookie? This allows us to restrict country fetching query to just one per session, neat huh? ;)
$countrycode = $cookie->getKey("visitor", "countrycode");
if (trim($countrycode) == "none") {
	// No country was available for this user so do nothing
	$country["countrycode"] = "";
	$country["country"] = "";
} else if (trim($countrycode) != "none" && trim($countrycode) != "") {
	// We have a country set
	$country["countrycode"] = $countrycode;
	$country["country"] = $cookie->getKey("visitor", "countryname");
} else {
	// No Country set
	$countrydata = getCountry($_SERVER["REMOTE_ADDR"]);

	if (trim($countrydata["countrycode2"]) != "") {
		$cookie->addCookie("visitor", "countrycode", strtolower($countrydata["countrycode2"]));
		$cookie->addCookie("visitor", "countryname", $countrydata["countryname"]);
		$country["countrycode"] = strtolower($countrydata["countrycode2"]);
		$country["country"] = $countrydata["countryname"];
	} else {
		// No country available for this ip, set to none so this query isnt executed for any other page this visitor loads
		$cookie->addCookie("visitor", "countrycode", "none");
		$cookie->addCookie("visitor", "countryname", "none");
		$country["countrycode"] = "";
		$country["country"] = "";
	}
	$cookiebuild = true;
}

// We only execute the note query if we havent checked for that already
if ($cookie->getKey("visitor", "notecheck") != "1")
{
	// Does this visitor have a note attached to him?
	$_note = $dbCore->queryFetch("SELECT COUNT(*) as totalnotes FROM `". TABLE_PREFIX ."visitornotes` WHERE ipaddress = '". $dbCore->escape($_SERVER["REMOTE_ADDR"]) ."' LIMIT 1;");
	if ($_note["totalnotes"] > 0)
	{
		$hasnotes = "1";
	} else {
		$hasnotes = "0";
	}
	$cookie->addCookie("visitor", "notecheck", "1");
	$cookiebuild = true;
}

$_campaign = array();
$campaignid = $cookie->getKey("visitor", "campaignid");
if (!empty($campaignid))
{
	$_campaign["campaignid"] = $cookie->getKey("visitor", "campaignid");
	$_campaign["title"] = $cookie->getKey("visitor", "campaigntitle");
}

if ($cookiebuild == true)
{
	$cookie->buildCookie("visitor");
}

// Update this session last activity
$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."sessions` SET `lastactivity` = '". DATENOW ."' WHERE `sessionid` = '". $dbCore->escape($sessionid) ."';");

// ======= JAVASCRIPT STARTS =======
?>
//===============================
// LiveResponse
// Copyright (c) 2001-<?php echo date("Y"); ?>
//===============================

<?php
if ($isbanned == true)
{
	// End right here, dont display anything.
	exit;
}




ob_start();
?>
var sessionid = "<?php echo $sessionid; ?>";
var country = "<?php echo $country["country"];?>";
var countrycode = "<?php echo $country["countrycode"];?>";
var hasnotes = "<?php echo $hasnotes; ?>";
var campaignid = "<?php echo $_campaign["campaignid"]; ?>";
var campaigntitle = "<?php echo $_campaign["title"]; ?>";
var isfirsttime = 1;
var timer = 0;
var imagefetch = <?php echo $_SWIFT["settings"]["livesupport_clientpagerefresh"]-1; ?>;
var image1;
var updateurl = "";
var screenHeight = window.screen.availHeight;
var screenWidth = window.screen.availWidth;
var colorDepth = window.screen.colorDepth;
var timeNow = new Date();
var referrer = escape(document.referrer);
var windows, mac, linux;
var ie, op, moz, misc, browsercode, browsername, browserversion, operatingsys;
var dom, ienew, ie4, ie5, ie6, moz_rv, moz_rv_sub, ie5mac, ie5xwin, opnu, op4, op5, op6, op7, saf, konq;
var appName, appVersion, userAgent;
var appname = navigator.appName;
var appVersion = navigator.appVersion;
var userAgent = navigator.userAgent;
var dombrowser = "default";
var isChatRunning = 0;
var title = document.title;
var proactiveImageUse = new Image();
windows = (appVersion.indexOf('Win') != -1);
mac = (appVersion.indexOf('Mac') != -1);
linux = (appVersion.indexOf('Linux') != -1);
if (!document.layers) {
	dom = (document.getElementById ) ? document.getElementById : false;
} else {
	dom = false;
}
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement &&
      ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
winH = myHeight;
winW = myWidth;
misc=(appVersion.substring(0,1) < 4);
op=(userAgent.indexOf('Opera') != -1);
moz=(userAgent.indexOf('Gecko') != -1);
ie=(document.all && !op);
saf=(userAgent.indexOf('Safari') != -1);
konq=(userAgent.indexOf('Konqueror') != -1);

if (op) {
	op_pos = userAgent.indexOf('Opera');
	opnu = userAgent.substr((op_pos+6),4);
	op5 = (opnu.substring(0,1) == 5);
	op6 = (opnu.substring(0,1) == 6);
	op7 = (opnu.substring(0,1) == 7);
} else if (moz){
	rv_pos = userAgent.indexOf('rv');
	moz_rv = userAgent.substr((rv_pos+3),3);
	moz_rv_sub = userAgent.substr((rv_pos+7),1);
	if (moz_rv_sub == ' ' || isNaN(moz_rv_sub)) {
		moz_rv_sub='';
	}
	moz_rv = moz_rv + moz_rv_sub;
} else if (ie){
	ie_pos = userAgent.indexOf('MSIE');
	ienu = userAgent.substr((ie_pos+5),3);
	ie4 = (!dom);
	ie5 = (ienu.substring(0,1) == 5);
	ie6 = (ienu.substring(0,1) == 6);
}

if (konq) {
	browsercode = "KO";
	browserversion = appVersion;
	browsername = "Konqueror";
} else if (saf) {
	browsercode = "SF";
	browserversion = appVersion;
	browsername = "Safari";
} else if (op) {
	browsercode = "OP";
	if (op5) {
		browserversion = "5";
	} else if (op6) {
		browserversion = "6";
	} else if (op7) {
		browserversion = "7";
	} else {
		browserversion = appVersion;
	}
	browsername = "Opera";
} else if (moz) {
	browsercode = "MO";
	browserversion = appVersion;
	browsername = "Mozilla";
} else if (ie) {
	browsercode = "IE";
	if (ie4) {
		browserversion = "4";
	} else if (ie5) {
		browserversion = "5";
	} else if (ie6) {
		browserversion = "6";
	} else {
		browserversion = appVersion;
	}
	browsername = "Internet Explorer";
}

if (windows) {
	operatingsys = "Windows";
} else if (linux) {
	operatingsys = "Linux";
} else if (mac) {
	operatingsys = "Mac";
} else {
	operatingsys = "Unkown";
}

if (document.getElementById)
{
	dombrowser = "default";
} else if (document.layers) {
	dombrowser = "NS4";
} else if (document.all) {
	dombrowser = "IE4";
}

function browserObject(objid)
{
	if (dombrowser == "default")
	{
		return document.getElementById(objid);
	} else if (dombrowser == "NS4") {
		return document.layers[objid];		
	} else if (dombrowser == "IE4") {
		return document.all[objid];
	}
}

function doRand()
{
	var num;
	now=new Date();
	num=(now.getSeconds());
	num=num+1;
	return num;
}

function getCookie(name) {
	var crumb = document.cookie;
	var index = crumb.indexOf(name + "=");
	if (index == -1) return null;
	index = crumb.indexOf("=", index) + 1;
	var endstr = crumb.indexOf(";", index);
	if (endstr == -1) endstr = crumb.length;
	return unescape(crumb.substring(index, endstr));
}

function deleteCookie(name) {
	var expiry = new Date();
	document.cookie = name + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT" +  "; path=/";
}

function elapsedTime()
{
	if (timer < 3600)
	{
		timer++;
		imagefetch++;

		if (imagefetch > <?php echo $_SWIFT["settings"]["livesupport_clientpagerefresh"]; ?>) {
			imagefetch = 0;
			doStatusLoop();
		}

		setTimeout("elapsedTime();", 1000);
	}
}

function doStatusLoop() {
	date1 = new Date();
	updateurl = "<?php echo $_SWIFT["swiftpath"] ?>visitor/index.php?_m=livesupport&_a=updatefootprint&time="+date1.getTime()+"&rand="+doRand()+"&url="+escape(window.location)+"&isfirsttime="+isfirsttime+"&sessionid="+sessionid+"&referrer="+escape(document.referrer)+"&resolution="+screenWidth+"x"+screenHeight+"&colordepth="+escape(colorDepth)+"&platform="+escape(navigator.platform)+"&appversion="+escape(navigator.appVersion)+"&appname="+escape(navigator.appName)+"&browsercode="+escape(browsercode)+"&browserversion="+escape(browserversion)+"&browsername="+escape(browsername)+"&operatingsys="+escape(operatingsys)+"&pagetitle="+escape(title)+"&country="+escape(country)+"&countrycode="+escape(countrycode)+"&hasnotes="+escape(hasnotes)+"&campaignid="+escape(campaignid)+"&campaigntitle="+escape(campaigntitle);
//	alert(updateurl);

	proactiveImageUse = new Image();
	proactiveImageUse.src = updateurl;

//	window.location.href = updateurl;

	proactiveImageUse.onload = imageLoaded;

	isfirsttime = 0;
}

function startChat(proactive)
{
	isChatRunning = 1;

	docWidth = (winW-<?php echo $_SWIFT["settings"]["livesupport_chatwidth"];?>)/2;
	docHeight = (winH-<?php echo $_SWIFT["settings"]["livesupport_chatheight"]; ?>)/2;
	chatwindow = window.open("<?php echo $_SWIFT["swiftpath"];?>visitor/index.php?_m=livesupport&_a=startclientchat&sessionid="+sessionid+"&proactive="+proactive+"&departmentid=<?=$_GET["departmentid"]?>&randno="+doRand()+"&fullname=<?=urlencode($_GET["fullname"])?>&email=<?=urlencode($_GET["email"])?>","customerchat"+doRand(), "toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=0,resizable=1,width=<?php echo $_SWIFT["settings"]["livesupport_chatwidth"];?>,height=<?php echo $_SWIFT["settings"]["livesupport_chatheight"]; ?>,left="+docWidth+",top="+docHeight);

	hideProactiveChatData();
}

function imageLoaded() {
	if (!proactiveImageUse)
	{
		return;
	}
	proactiveAction = proactiveImageUse.width;

	if (proactiveAction == 3)
	{
		doProactiveForced();
	} else if (proactiveAction == 4) {
		displayProactiveChatData();
	} else {
	}
}

function writeProactiveRequestData()
{
	docWidth = (winW-450)/2;
	docHeight = (winH-400)/2;
	classData = "DISPLAY: none; FLOAT: left; POSITION: absolute; TOP:"+docHeight+"px; LEFT:"+docWidth+"px; WIDTH: 450px; HEIGHT: 400px; Z-INDEX: 500;";
	writedata = "<style type=\"text/css\"> <!-- #proactivechatdiv { "+classData+" } --> </style>";
	writedata += "<div id=\"proactivechatdiv\" style=\""+classData+"\">";
	<?
	$proactivetmpl = $template->displayTemplate("proactivechatdiv");
	echo HTML2JS($proactivetmpl, "writedata += ", false, false);
	?>
	writedata += "</div>";
	document.write(writedata);
}

function displayProactiveChatData()
{
	writeObj = browserObject("proactivechatdiv");
	if (writeObj)
	{
		docWidth = (winW-450)/2;
		docHeight = (winH-400)/2;
		writeObj.top = docWidth;
		writeObj.left = docHeight;
	}
	switchDisplay("proactivechatdiv");
}

function hideProactiveChatData()
{
	hideDisplay("proactivechatdiv");
}

function doProactiveForced()
{
	switchDisplay("proactivechatdiv");
	startChat("<?=PROACTIVE_FORCED?>");
}

function doProactiveRequest()
{
	startChat("<?=PROACTIVE_REQUEST?>");
}

function closeProactiveRequest()
{
	rejectProactive = new Image();
	date1 = new Date();
	rejectProactive.src = "<?php echo $_SWIFT["swiftpath"]; ?>visitor/index.php?_m=livesupport&_a=resetproactivestatus&time="+date1.getTime()+"&rand="+doRand()+"&sessionid="+sessionid;

	hideProactiveChatData();
}

function switchDisplay(objid)
{
	result = browserObject(objid);
	if (!result)
	{
		return;
	}

	if (result.style.display == "none")
	{
		result.style.display = "block";
	} else {
		result.style.display = "none";
	}
}

function hideDisplay(objid)
{
	result = browserObject(objid);
	if (!result)
	{
		return;
	}

	result.style.display = "none";
}

function resetChatStatus()
{
	isChatRunning = 0;
}

function runURL(url)
{
	runURLImg = new Image();
	date1 = new Date();
	runURLImg.src = url;
}

writeProactiveRequestData();
elapsedTime();
<?
if ($_GET["custom"] != "")
{
	$dataarray = unserialize(base64_decode($_GET["custom"]));
	if (is_array($dataarray))
	{
		$template->assign("iscustomcode", "true");
		$template->assign("onlinetext", $dataarray[0]);
		$template->assign("offlinetext", $dataarray[1]);
	} else {
		$template->assign("iscustomcode", "false");
	}
}
?>
document.write("<?php echo addslashes(str_replace("\n", "", str_replace("\r\n", "\n",$template->displayTemplate("chatimage")))); ?>");
<?php
$contents = ob_get_contents();
ob_end_clean();
//$replace = array("\r\n", "  ", "	");
//$with = array("", " ", " ");
echo str_replace($replace, $with, $contents);
?>